﻿using HelperTool_WHW;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MainFrame
{
    public partial class FormMainPage : Form
    {
        public DateTime labelTime = DateTime.Now;
        public DateTime cutTime = DateTime.Now;
        public FormMainPage()
        {
            InitializeComponent();
        }
        bool IsFirst = true;
        private void FormMainPage_Load(object sender, EventArgs e)
        {
            if(IsFirst)
            {
                IsFirst = false;
                Task.Factory.StartNew(DisplayStatus);
                displalyInfo.displayInfoMain += displayInfo;
                displalyInfo.displayInfoMainBox += displayInfo;
                displalyInfo.displayErrorMain += displayErrorInfo;
                GlobalVar.displayCycleTime_Cut += displayCT_cut;
                GlobalVar.displayCycleTime_Label += displayCT_label;
                GlobalVar.displayCycleTime_CutReal += displayCT_cutReal;
                GlobalVar.displayCycleTime_LabelReal += displayCT_labelReal;
                displalyInfo.addInfoRow = addRowToDisplay;//关联信息提示全局变量
            }
        }
        public void displayCT_cut()
        {
            this.BeginInvoke(new Action(() =>
            {
                var str = ((DateTime.Now - GlobalVar.StartTime_Cut).TotalMilliseconds / (double)1000).ToString("F03");
                tbx_CT_cut.Text = str;
            }));
        }
        public void displayCT_label()
        {
            this.BeginInvoke(new Action(() =>
            {
                var str = ((DateTime.Now - GlobalVar.StartTime_Label).TotalMilliseconds / (double)1000).ToString("F03");
                tbx_CT_Label.Text = str;
            }));
        }
        public void displayCT_cutReal ()
        {
            this.BeginInvoke(new Action(() =>
            {
                var str = ((DateTime.Now - cutTime).TotalMilliseconds / (double)1000).ToString("F03");
                cutTime= DateTime.Now;
                tbx_CT_CutReal.Text = str;
            }));
        }
        public void displayCT_labelReal()
        {
            this.BeginInvoke(new Action(() =>
            {
                var str = ((DateTime.Now - labelTime).TotalMilliseconds / (double)1000).ToString("F03");
                labelTime = DateTime.Now;
                tbx_CT_LabelReal.Text = str;
            }));
        }
        public void addRowToDisplay(ProductInfo info)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    GlobalVar.closeSave.Count++;
                    //  if (info.Result_down ==e_Result.出料OK.ToString()|| info .Result== e_Result.写入读卡器OK.ToString() || info.Result == e_Result.贴膜OK.ToString())
                    if (!info.Result_Label.Contains("NG"))
                        GlobalVar.closeSave.OKCount++;
                    else
                        GlobalVar.closeSave.NGCount++;

                    var rCount = dgv_display.Rows.Count;
                    //if (rCount > 0)
                    //    rCount = Convert.ToInt32(dgv_display.Rows[rCount - 1].Cells[0].Value.ToString());
                    if (rCount > 500)
                        dgv_display.Rows.Clear();
                   
                    dgv_display.Rows.Add( info.ProId, info.ProNo, 
                        info.LaserTime == null ? "" : info.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss"), 
                        info.LabelTime == null ? "" : info.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss"), 
                        info.typeName, info.Result_up, info.Result_down, info.Result, info.Result_Cut, info.Result_Label);
                    dgv_display.FirstDisplayedScrollingRowIndex = dgv_display.Rows.Count - 1;
                }));
               
                WriteCSV(info);
                 var ret = GlobalVar.sqlHelper.insert<ProductInfo>(GlobalVar.userConfig.db_T_Product, info);
                if(GlobalVar.userConfig.UploadInfo.IsUploadUrl)
                {
                    if(!string.IsNullOrEmpty(GlobalVar.userConfig.UploadInfo.url_DataUpload)&&GlobalVar.motionConfig.boxReadInfo.IsEnable)
                    {
                        if (!string.IsNullOrEmpty(info.ProId) && info.ProId.Length >= GlobalVar.motionConfig.boxReadInfo.minLength)
                        {
                            Task.Run(new Action(() =>
                            {
                                UploadInterface.upload_DataUpload(info);
                            }));
                        }
                        else
                        {
                            displalyInfo.displayInfoMain($"读卡器ID内容太短不进行上传{info.ProId}");
                        }
                    }
                       
                }
                displalyInfo.displayInfoMain(ret==1?"插入生产数据成功":"插入生产数据失败");
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain("显示数据：" + ex.Message);
            }
        }
        string path_Save = Environment.CurrentDirectory + "\\CSV";
        public void WriteCSV(ProductInfo info)
        {
            if (!Directory.Exists(path_Save))
            {
                Directory.CreateDirectory(path_Save);
            }
            string saveDate = DateTime.Now.ToString("yyyy_MM_dd");
            var filepath = path_Save + "\\" + saveDate + ".CSV";
            var str_Start = info.LaserTime == null ? "" : info?.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss");
            var str_End = info.LabelTime == null ? "" : info?.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss");
            var proid = info.ProId == null ? "" : info.ProId;
            var str = info.ProNo.ToString() + "," + proid + "," + str_Start + "," + str_End + "," + info.typeName + "," + info.Result.ToString() + "," 
                + info.Result_up.ToString() + "," + info.Result_down.ToString() + "," + info.Result_Cut.ToString() + "," + info.Result_Label.ToString();
         
            if (!File.Exists(filepath))
            {
                FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
                StreamWriter csvStreamWriter = new StreamWriter(fs,  Encoding.UTF8);
                csvStreamWriter.WriteLine("平台号,工装ID,开始时间,结束时间,生产配方,上游结果,下游结果,结果,撕膜结果,贴标结果");
                csvStreamWriter.WriteLine(str);
                csvStreamWriter.Flush();
                csvStreamWriter.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(filepath, FileMode.Append);
                StreamWriter csvStreamWriter = new StreamWriter(fs, Encoding.UTF8);
                csvStreamWriter.WriteLine(str);
                csvStreamWriter.Flush();
                csvStreamWriter.Close();
                fs.Close();
            }
           
        }
        private void displayInfo(string msg)
        {
            try
            {
                this.BeginInvoke(new Action(() =>
            {
                if(rbx_msg.Lines.Length > 500)
                rbx_msg.Text = "";
                rbx_msg.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + Environment.NewLine + msg + Environment.NewLine);
                rbx_msg.ScrollToCaret();
            }));
            }
            catch (Exception ex)
            {
                LogNetHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + Environment.NewLine + msg);
            }
        }
        private void displayErrorInfo(string msg)
        {
            try
            {
                this.BeginInvoke(new Action(() =>
                {
                    if (rbx_error.Lines.Length > 500)
                        rbx_error.Text = "";
                    rbx_error.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + Environment.NewLine + msg + Environment.NewLine);
                    rbx_error.ScrollToCaret();
                }));
            }catch(Exception ex)
            {
                LogNetHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + Environment.NewLine + msg);
            }
           
        }
        private void DisplayStatus()
        {
            try
            {
                while (!GlobalVar.isExit)
                {
                    Thread.Sleep(300);
                    this.BeginInvoke(new Action(() => {
                        btn_ProDownStatus.BackColor = GlobalMotion.Input_CardEx2[(int)e_input_extCard2.下输送治具检测1] ? Color.Green : Color.Gray;
                        if (GlobalVar.isAutoRun && !GlobalVar.isPause)
                        {
                            GlobalVar.IsStatusAuto = true;
                            switchButton1.SetColor(Color.Green);
                            switchButton1.text = "运行中";
                        }
                        else if (GlobalVar.isAutoRun && GlobalVar.isPause)
                        {
                            switchButton1.SetColor(Color.Orange);
                            switchButton1.text = "暂停中";
                            if (GlobalVar.userConfig.isEnableUpSignal)
                            {
                                if (GlobalMotion.Output_Card1[(int)e_output_card1.上层向上游要料])
                                {
                                    GlobalMotion.Card_1.setOut((int)e_output_card1.上层向上游要料, MotionControl.e_out_OnOff.on);
                                }
                               
                            }
                            if (GlobalVar.userConfig.isEnableDownSignal)
                            {
                                if (GlobalMotion.Output_Card1[(int)e_output_card1.下层要料])
                                {
                                    GlobalMotion.Card_1.setOut((int)e_output_card1.下层要料, MotionControl.e_out_OnOff.on);
                                }
                            }
                        }
                        else if (GlobalVar.isEstop)
                        {
                            GlobalVar.IsStatusAuto = false;
                            switchButton1.SetColor(Color.Red);
                            switchButton1.text = "报警中";
                            if(GlobalVar.userConfig.isEnableUpSignal)
                            {
                                if (GlobalMotion.Output_Card1[(int)e_output_card1.上层向上游要料])
                                {
                                    GlobalMotion.Card_1.setOut((int)e_output_card1.上层向上游要料, MotionControl.e_out_OnOff.on);
                                }
                            }
                            if (GlobalVar.userConfig.isEnableDownSignal)
                            {
                                if (GlobalMotion.Output_Card1[(int)e_output_card1.下层要料])
                                {
                                    GlobalMotion.Card_1.setOut((int)e_output_card1.下层要料, MotionControl.e_out_OnOff.on);
                                }
                            }
                        }
                        else
                        {
                            switchButton1.SetColor(Color.Yellow);
                            switchButton1.text = "空闲中";
                        }
                        LeftResult.BackColor = GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测2] ? Color.Green : Color.Gray; ;
                        RightResult.BackColor = GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测3] ? Color.Green : Color.Gray;
                        chartYiledRate1.ProduceOKNum = GlobalVar.closeSave.OKCount;
                        chartYiledRate1.ProduceNGNum = GlobalVar.closeSave.NGCount;
                        var count = GlobalVar.closeSave.OKCount + GlobalVar.closeSave.NGCount;
                        if ((count) < 1)
                        {
                            chartYiledRate1.SetMonthOkRate = 100;
                            chartYiledRate1.SetDayOkRate = 100;
                        }
                        else
                        {
                            chartYiledRate1.SetDayOkRate = (double)(GlobalVar.closeSave.OKCount * 100) / (double)count;
                            chartYiledRate1.SetMonthOkRate = (double)(GlobalVar.closeSave.OKCount * 100) / (double)count;
                        }
                    }));
                }
            }catch(Exception ex)
            {
                LogNetHelper.WriteLog(ex);
            }
           
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            GlobalVar.closeSave.Count = 0;
            GlobalVar.closeSave.OKCount = 0;
            GlobalVar.closeSave.NGCount = 0;
            dgv_display.Rows.Clear();
        }

        private void label11_Click(object sender, EventArgs e)
        {

        }
    }
}
